<?php

namespace App\Services\WxCard;

use App\Models\WxCardAdvance;
use App\Models\WxCardBase;
use App\Models\WxCardReceive;
use App\Models\WxCardTransfer;
use App\Services\WxCardService;
use App\Services\WxMaterial\WxMaterialNews;

/**
 * 微信卡券抽象类
 * @package App\Services\WxCard
 */
abstract class WxCardAbstract implements WxCardInterface
{
    protected $data;//资源数据
    protected $name = '';
    protected $cardKeyList = [
        'none' => '暂无',
    ];

    /**
     * 获取会员卡名称
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * 获取卡券标识列表
     * @return array
     */
    public function getCardKeyList()
    {
        $list = [];
        if (!empty($this->cardKeyList)) {
            foreach ($this->cardKeyList as $k => $v) {
                $list[] = ['type' => $k, 'name' => $v];
            }
        }
        return $list;
    }
    /**
     * 保存卡券基本数据
     * @param $request
     * @return integer card_base_id 卡券主键ID
     */
    protected function saveBase($request)
    {
        $cardBaseId = $request->base['card_base_id'] ?? 0;
        if ($cardBaseId) {
            $baseModel = WxCardBase::findOrFail($cardBaseId);
            if (in_array($baseModel->audit_status, [WxCardService::CARD_STATUS_NOT_VERIFY])) {
                throw new \Exception('改状态下的卡券不能编辑');
            }
        } else {
            $baseModel = new WxCardBase;
        }
        //保存卡券基本数据
        $baseModel->card_type = $request->base['card_type'] ?? '';
        $baseModel->card_key = $request->base['card_key'] ?? '';
        $baseModel->logo_url = $request->base['logo_url'] ?? '';
        $baseModel->code_type = $request->base['code_type'] ?? '';
        $baseModel->brand_name = $request->base['brand_name'] ?? '';
        $baseModel->title = $request->base['title'] ?? '';
        $baseModel->color = $request->base['color'] ?? '';
        $baseModel->notice = $request->base['notice'] ?? '';
        $baseModel->description = $request->base['description'] ?? '';
        $baseModel->date_info = $request->base['date_info'] ?? [];
        //库存
        $sku = $request->base['sku'] ?? ['quantity' => 0, 'total_quantity' => 0];
        empty($sku['total_quantity']) && $sku['total_quantity'] = $sku['quantity'];
        $baseModel->sku = $sku;

        $baseModel->use_custom_code = (int)$request->base['use_custom_code'] ?? 0;
        $baseModel->get_custom_code_mode = $request->base['get_custom_code_mode'] ?? '';
        $baseModel->bind_openid = (int)isset($request->base['bind_openid']) ? $request->base['bind_openid'] : 0;
        $baseModel->service_phone = $request->base['service_phone'] ?? '';
        $baseModel->use_all_locations = (int)isset($request->base['use_all_locations']) ? $request->base['use_all_locations'] : 0;
        $baseModel->location_id_list = isset($request->base['location_id_list']) ? $request->base['location_id_list'] : [];
        $baseModel->center_info = $request->base['center_info'] ?? [];
        $baseModel->custom_info = $request->base['custom_info'] ?? [];
        $baseModel->promotion_info = $request->base['promotion_info'] ?? [];
        $baseModel->get_limit = (int)$request->base['get_limit'] ?? 0;
        $baseModel->use_limit = (int)$request->base['use_limit'] ?? 0;
        $baseModel->can_share = (int)$request->base['can_share'] ?? 0;
        $baseModel->can_give_friend = (int)$request->base['can_give_friend'] ?? 0;
        $baseModel->audit_status = WxCardService::CARD_STATUS_NOPUBLISH;
        $baseModel->save();
        $cardBaseId = $baseModel->card_base_id;
        //保存卡券高级字段数据
        $advanceId = $request->advance['id'] ?? 0;
        if ($advanceId) {
            $advanceModel = WxCardAdvance::findOrFail($advanceId);
        } else {
            $advanceModel = new WxCardAdvance;
        }
        $advanceModel->card_base_id = $cardBaseId;
        $advanceModel->use_condition = $request->advance['use_condition'] ?? [];
        $advanceModel->abstract = $request->advance['abstract'] ?? [];
        $advanceModel->text_image_list = $request->advance['text_image_list'] ?? [];
        $advanceModel->time_limit = $request->advance['time_limit'] ?? [];
        $advanceModel->business_service = $request->advance['business_service'] ?? [];
        $advanceModel->share_friends = (int) $request->advance['share_friends'] ?? 0;
        $advanceModel->save();

        return $cardBaseId;
    }

    /**
     * 通过数据库数据组装接口发布数据
     * @param $data
     */
    protected function buildCommonApiPostData($data)
    {
        $baseInfo = [];
        $advancedInfo = [];
        //商户名字(不可修改)
        if (!empty($data['brand_name']) && empty($data['card_id'])) {
            $baseInfo['brand_name'] = $data['brand_name'];
        }
        //卡券名(不可修改)
        if (!empty($data['title']) && empty($data['card_id'])) {
            $baseInfo['title'] = $data['title'];
        }
        //码型(可修改)
        !empty($data['code_type']) && $baseInfo['code_type'] = $data['code_type'];
        //卡券的商户logo(可修改)
        if (!empty($data['logo_url'])) {
            $baseInfo['logo_url'] = (new WxMaterialNews())->getWxViewUrl($data['logo_url']);
        }
        //券颜色(可修改)
        !empty($data['color']) && $baseInfo['color'] = $data['color'];
        //卡券使用提醒(可修改)
        !empty($data['notice']) && $baseInfo['notice'] = $data['notice'];
        //卡券使用说明(可修改)
        !empty($data['description']) && $baseInfo['description'] = $data['description'];
        //客服电话(可修改)
        !empty($data['service_phone']) && $baseInfo['service_phone'] = $data['service_phone'];
        //使用日期，有效期的信息
        if (!empty($data['date_info']['type'])) {
            //固定日期区间(可修改)
            if ($data['date_info']['type'] == 'DATE_TYPE_FIX_TIME_RANGE') {
                !empty($data['date_info']['type']) && $baseInfo['date_info']['type'] = $data['date_info']['type'];
                !empty($data['date_info']['begin_timestamp']) && $baseInfo['date_info']['begin_timestamp'] = strtotime($data['date_info']['begin_timestamp']);
                !empty($data['date_info']['end_timestamp']) && $baseInfo['date_info']['end_timestamp'] = strtotime($data['date_info']['end_timestamp']);
            }
            //固定时长（不可修改）
            if ($data['date_info']['type'] == 'DATE_TYPE_FIX_TERM' && empty($data['card_id'])) {
                !empty($data['date_info']['type']) && $baseInfo['date_info']['type'] = $data['date_info']['type'];
                !empty($data['date_info']['fixed_term']) && $baseInfo['date_info']['fixed_term'] = $data['date_info']['fixed_term'];
                isset($data['date_info']['fixed_begin_term']) && $baseInfo['date_info']['fixed_begin_term'] = (int) $data['date_info']['fixed_begin_term'];
                !empty($data['date_info']['end_timestamp']) && $baseInfo['date_info']['end_timestamp'] = strtotime($data['date_info']['end_timestamp']);
            }
        }
        //商品信息（不可修改）
        if (empty($data['card_id'])) {
            isset($data['sku']['quantity']) && $baseInfo['sku']['quantity'] = $data['sku']['quantity'];
        }
        //使用限制（不可修改）
        if (empty($data['card_id'])) {
            isset($data['use_limit']) && $baseInfo['use_limit'] = (int)$data['use_limit'];
        }
        //（可修改）
        isset($data['get_limit']) && $baseInfo['get_limit'] = (int)$data['get_limit'];
        isset($data['can_share']) && $baseInfo['can_share'] = (bool)$data['can_share'];
        isset($data['can_give_friend']) && $baseInfo['can_give_friend'] = (bool)$data['can_give_friend'];
        !empty($data['location_id_list']) && $baseInfo['location_id_list'] = (array)$data['location_id_list'];
        //是否自定义Code码（不可修改）
        if (empty($data['card_id'])) {
            isset($data['use_custom_code']) && $baseInfo['use_custom_code'] = (bool)$data['use_custom_code'];
            !empty($data['get_custom_code_mode']) && $baseInfo['get_custom_code_mode'] = $data['get_custom_code_mode'];
            isset($data['bind_openid']) && $baseInfo['bind_openid'] = (bool)$data['bind_openid'];
        }
        //卡券顶部居中的按钮（可修改）
        !empty($data['center_info']['center_title']) && $baseInfo['center_title'] = $data['center_info']['center_title'];
        !empty($data['center_info']['center_sub_title']) && $baseInfo['center_sub_title'] = $data['center_info']['center_sub_title'];
        !empty($data['center_info']['center_url']) && $baseInfo['center_url'] = $data['center_info']['center_url'];
        !empty($data['center_info']['center_app_brand_user_name']) && $baseInfo['center_app_brand_user_name'] = $data['center_info']['center_app_brand_user_name'];
        !empty($data['center_info']['center_app_brand_pass']) && $baseInfo['center_app_brand_pass'] = $data['center_info']['center_app_brand_pass'];
        //自定义跳转入口（可修改）
        !empty($data['custom_info']['custom_url_name']) && $baseInfo['custom_url_name'] = $data['custom_info']['custom_url_name'];
        !empty($data['custom_info']['custom_url_sub_title']) && $baseInfo['custom_url_sub_title'] = $data['custom_info']['custom_url_sub_title'];
        !empty($data['custom_info']['custom_url']) && $baseInfo['custom_url'] = $data['custom_info']['custom_url'];
        !empty($data['custom_info']['custom_app_brand_user_name']) && $baseInfo['custom_app_brand_user_name'] = $data['custom_info']['custom_app_brand_user_name'];
        !empty($data['custom_info']['custom_app_brand_pass']) && $baseInfo['custom_app_brand_pass'] = $data['custom_info']['custom_app_brand_pass'];
        //营销场景的自定义入口（可修改）
        !empty($data['promotion_info']['promotion_url_name']) && $baseInfo['promotion_url_name'] = $data['promotion_info']['promotion_url_name'];
        !empty($data['promotion_info']['promotion_url_sub_title']) && $baseInfo['promotion_url_sub_title'] = $data['promotion_info']['promotion_url_sub_title'];
        !empty($data['promotion_info']['promotion_url']) && $baseInfo['promotion_url'] = $data['promotion_info']['promotion_url'];
        !empty($data['promotion_info']['promotion_app_brand_user_name']) && $baseInfo['promotion_app_brand_user_name'] = $data['promotion_info']['promotion_app_brand_user_name'];
        !empty($data['promotion_info']['promotion_app_brand_pass']) && $baseInfo['promotion_app_brand_pass'] = $data['promotion_info']['promotion_app_brand_pass'];

        $advancedData = $data['advance'];
        //高级字段（不可修改）
        if (empty($data['card_id']) && !empty($data['advance'])) {
            //使用门槛（条件）字段
            if ($advancedData['use_condition']['islimit'] == 1) {
                isset($advancedData['use_condition']['can_use_with_other_discount']) && $advancedInfo['use_condition']['can_use_with_other_discount'] = (bool)$advancedData['use_condition']['can_use_with_other_discount'];
                !empty($advancedData['use_condition']['accept_category']) && $advancedInfo['use_condition']['accept_category'] = $advancedData['use_condition']['accept_category'];
                !empty($advancedData['use_condition']['reject_category']) && $advancedInfo['use_condition']['reject_category'] = $advancedData['use_condition']['reject_category'];
                isset($advancedData['use_condition']['least_cost']) && $advancedInfo['use_condition']['least_cost'] = (int)$advancedData['use_condition']['least_cost'];
                !empty($advancedData['use_condition']['object_use_for']) && $advancedInfo['use_condition']['object_use_for'] = $advancedData['use_condition']['object_use_for'];
            }
            //封面摘要
            !empty($advancedData['abstract']['abstract']) && $advancedInfo['abstract']['abstract'] = $advancedData['abstract']['abstract'];
            !empty($advancedData['abstract']['icon_url_list']) && $advancedInfo['abstract']['icon_url_list'] = $advancedData['abstract']['icon_url_list'];
            //图文列表
            if (!empty($advancedData['text_image_list'])) {
                foreach ($advancedData['text_image_list'] as $v) {
                    $advancedInfo['text_image_list'][] = [
                        'image_url' => !empty($v['view_url']) ? (new WxMaterialNews())->getWxViewUrl($v['view_url']) : '',
                        'text' => $v['name'] ?? '',
                    ];
                }
            }
            //商家服务类型
            !empty($advancedData['business_service']) && $advancedInfo['business_service'] = array_values((array)$advancedData['business_service']);
            //使用时段限制
            if (!empty($advancedData['time_limit'])) {
                foreach ($advancedData['time_limit'] as $v) {
                    if (isset($v['isopen']) && $v['isopen'] == 1) {
                        $timeLimitData = ['type' => $v['type']];
                        if (isset($v['begin_hour']) && is_integer($v['begin_hour'])) {
                            $timeLimitData['begin_hour'] = (int)$v['begin_hour'];
                            $timeLimitData['begin_minute'] = (int)$v['begin_minute'];
                        }
                        if (isset($v['end_hour']) && is_integer($v['end_hour'])) {
                            $timeLimitData['end_hour'] = (int)$v['end_hour'];
                            $timeLimitData['end_minute'] = (int)$v['end_minute'];
                        }
                        $advancedInfo['time_limit'][] = $timeLimitData;
                    }
                }
            }
        }
        return ['base_info' => $baseInfo, 'advanced_info' => $advancedInfo];
    }

    /**
     * 同步基础卡券数据
     * @param $cardInfo
     * @throws \Exception
     */
    protected function syncBase($cardInfo)
    {
        //卡券类型
        $cardType = !empty($cardInfo['card_type']) ? $cardInfo['card_type'] : '';
        $dataIndex = strtolower($cardType);
        //卡券基础数据
        $baseInfo = !empty($cardInfo[$dataIndex]['base_info']) ? $cardInfo[$dataIndex]['base_info'] : [];
        $cardId = !empty($baseInfo['id']) ? $baseInfo['id'] : '';
        if (empty($cardId)) {
            throw new \Exception('卡券ID不存在');
        }
        $baseModel = WxCardBase::where('card_id', $cardId)->first();
        if (empty($baseModel)) {
            $baseModel = new WxCardBase;
        }
        $baseModel->card_id = $cardId;
        $baseModel->card_type = $cardType;
        $baseModel->code_type = $baseInfo['code_type'] ?? '';
        $baseModel->brand_name = $baseInfo['brand_name'] ?? '';
        $baseModel->title = $baseInfo['title'] ?? '';
        //卡券的商户logo
        //抓取到本地
        !empty($baseInfo['logo_url']) && $baseModel->logo_url = (new WxMaterialNews())->getSelfViewUrl($baseInfo['logo_url']);
        //券颜色,转换为后台能识别的格式
        if (!empty($baseInfo['color'])) {
            $baseModel->color = (new WxCardService())->getColorNameByValue($baseInfo['color']);
        }
        $baseModel->notice = $baseInfo['notice'] ?? '';
        $baseModel->description = $baseInfo['description'] ?? '';
        //使用日期
        $dateInfo['type'] = !empty($baseInfo['date_info']['type']) ? $baseInfo['date_info']['type'] : 'DATETYPE_FIX_TERM';
        $dateInfo['begin_timestamp'] = !empty($baseInfo['date_info']['begin_timestamp']) ? date('Y-m-d H:i:s', (int) $baseInfo['date_info']['begin_timestamp']) : '';
        $dateInfo['end_timestamp'] = !empty($baseInfo['date_info']['end_timestamp']) ? date('Y-m-d H:i:s', (int) $baseInfo['date_info']['end_timestamp']) : '';
        $dateInfo['fixed_term'] = !empty($baseInfo['date_info']['fixed_term']) ? $baseInfo['date_info']['fixed_term'] : '';
        $dateInfo['fixed_begin_term'] = !empty($baseInfo['date_info']['fixed_begin_term']) ? $baseInfo['date_info']['fixed_begin_term'] : '';
        $baseModel->date_info = $dateInfo;
        //商品信息
        $sku['quantity'] = !empty($baseInfo['sku']['quantity']) ? (int)$baseInfo['sku']['quantity'] : 0;
        $sku['total_quantity'] = !empty($baseInfo['sku']['total_quantity']) ? (int)$baseInfo['sku']['total_quantity'] : 0;
        $baseModel->sku = $sku;

        $baseModel->use_custom_code = isset($baseInfo['use_custom_code']) ? (int)$baseInfo['use_custom_code'] : 0;
        $baseModel->get_custom_code_mode = isset($baseInfo['get_custom_code_mode']) ? $baseInfo['use_custom_code'] : '';
        $baseModel->bind_openid = isset($baseInfo['bind_openid']) ? (int)$baseInfo['bind_openid'] : 0;
        $baseModel->service_phone = isset($baseInfo['service_phone']) ? $baseInfo['service_phone'] : '';
        $baseModel->use_all_locations = isset($baseInfo['use_all_locations']) ? (int) $baseInfo['use_all_locations'] : 0;
        $baseModel->location_id_list = isset($baseInfo['location_id_list']) ? (array) $baseInfo['location_id_list'] : [];
        //卡券顶部居中的按钮信息
        $centerInfo['center_title'] = isset($baseInfo['center_title']) ? $baseInfo['center_title'] : '';
        $centerInfo['center_sub_title'] = isset($baseInfo['center_sub_title']) ? $baseInfo['center_sub_title'] : '';
        $centerInfo['center_url'] = isset($baseInfo['center_url']) ? $baseInfo['center_url'] : '';
        $centerInfo['center_app_brand_pass'] = isset($baseInfo['center_app_brand_pass']) ? $baseInfo['center_app_brand_pass'] : '';
        $centerInfo['center_app_brand_user_name'] = isset($baseInfo['center_app_brand_user_name']) ? $baseInfo['center_app_brand_user_name'] : '';
        $baseModel->center_info = $centerInfo;
        //自定义跳转信息
        $customInfo['custom_url_name'] = isset($baseInfo['custom_url_name']) ? $baseInfo['custom_url_name'] : '';
        $customInfo['custom_url_sub_title'] = isset($baseInfo['custom_url_sub_title']) ? $baseInfo['custom_url_sub_title'] : '';
        $customInfo['custom_url'] = isset($baseInfo['custom_url']) ? $baseInfo['custom_url'] : '';
        $customInfo['custom_app_brand_user_name'] = isset($baseInfo['custom_app_brand_user_name']) ? $baseInfo['custom_app_brand_user_name'] : '';
        $customInfo['custom_app_brand_pass'] = isset($baseInfo['custom_app_brand_pass']) ? $baseInfo['custom_app_brand_pass'] : '';
        $baseModel->custom_info = $customInfo;
        //营销场景入口信息
        $promotionInfo['promotion_url_name'] = isset($baseInfo['promotion_url_name']) ? $baseInfo['promotion_url_name'] : '';
        $promotionInfo['promotion_url_sub_title'] = isset($baseInfo['promotion_url_sub_title']) ? $baseInfo['promotion_url_sub_title'] : '';
        $promotionInfo['promotion_url'] = isset($baseInfo['promotion_url']) ? $baseInfo['promotion_url'] : '';
        $promotionInfo['promotion_app_brand_user_name'] = isset($baseInfo['promotion_app_brand_user_name']) ? $baseInfo['promotion_app_brand_user_name'] : '';
        $promotionInfo['promotion_app_brand_pass'] = isset($baseInfo['promotion_app_brand_pass']) ? $baseInfo['promotion_app_brand_pass'] : '';
        $baseModel->promotion_info = $promotionInfo;
        $baseModel->get_limit = isset($baseInfo['get_limit']) ? (int)$baseInfo['get_limit'] : 50;
        $baseModel->use_limit = isset($baseInfo['use_limit']) ? (int)$baseInfo['use_limit'] : 50;
        $baseModel->can_share = isset($baseInfo['can_share']) ? (int)$baseInfo['can_share'] : 0;
        $baseModel->can_give_friend = isset($baseInfo['can_give_friend']) ? (int)$baseInfo['can_give_friend'] : 0;
        //审核状态
        $statusMap = [
            'CARD_STATUS_NOT_VERIFY' => WxCardService::CARD_STATUS_NOT_VERIFY,
            'CARD_STATUS_VERIFY_FAIL' => WxCardService::CARD_STATUS_VERIFY_FAIL,
            'CARD_STATUS_VERIFY_OK' => WxCardService::CARD_STATUS_VERIFY_OK,
            'CARD_STATUS_DELETE' => WxCardService::CARD_STATUS_USER_DELETE,
            'CARD_STATUS_DISPATCH' => WxCardService::CARD_STATUS_DISPATCH,
        ];
        $baseModel->audit_status = !empty($baseInfo['status']) && isset($statusMap[$baseInfo['status']]) ? $statusMap[$baseInfo['status']] : WxCardService::CARD_STATUS_NOPUBLISH;
        $baseModel->save();

        $advanceInfo = !empty($cardInfo[$dataIndex]['advanced_info']) ? $cardInfo[$dataIndex]['advanced_info'] : [];
        //卡券高级字段
        $advanceModel = WxCardAdvance::where('card_base_id', $baseModel->card_base_id)->first();
        if (empty($advanceModel)) {
            $advanceModel = new WxCardAdvance();
        }
        $advanceModel->card_base_id = $baseModel->card_base_id;
        //使用门槛
        $useCondition['islimit'] = !empty($advanceInfo['use_condition']) ? 1 : 0;
        $useCondition['accept_category'] = $advanceInfo['accept_category'] ?? '';
        $useCondition['reject_category'] = $advanceInfo['reject_category'] ?? '';
        $useCondition['least_cost'] = $advanceInfo['least_cost'] ?? '';
        $useCondition['object_use_for'] = $advanceInfo['object_use_for'] ?? '';
        $useCondition['can_use_with_other_discount'] = $advanceInfo['can_use_with_other_discount'] ?? 0;
        $useCondition['can_use_with_membercard'] = $advanceInfo['can_use_with_membercard'] ?? 0;
        $advanceModel->use_condition = $useCondition;
        //封面摘要结构体名称
        $abstract['abstract'] = !empty($advanceInfo['abstract']['abstract']) ? $advanceInfo['abstract']['abstract'] : '';
        $abstract['icon_url_list'] = [];
        if (!empty($advanceInfo['abstract']['icon_url_list'])) {
            foreach ($advanceInfo['abstract']['icon_url_list'] as $icon) {
                $abstract['icon_url_list'][] = (new WxMaterialNews())->getSelfViewUrl($icon);
            }
        }
        $advanceModel->abstract = $abstract;
        //图文列表
        $textImageList = [];
        if (!empty($advanceInfo['text_image_list'])) {
            foreach ($advanceInfo['text_image_list'] as $item) {
                $textImageList[] = [
                    'view_url' => $item['image_url'] ? (new WxMaterialNews())->getSelfViewUrl($item['image_url']) : '',
                    'name' => $item['text'] ?? '',
                ];
            }
        }
        $advanceModel->text_image_list = $textImageList;
        //使用时段限制
        $timeLimit = [
            'MONDAY' => ['type' => 'MONDAY', 'isopen' => 0, 'name' => '周一', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
            'TUESDAY' => ['type' => 'TUESDAY', 'isopen' => 0, 'name' => '周二', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
            'WEDNESDAY' => ['type' => 'WEDNESDAY', 'isopen' => 0, 'name' => '周三', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
            'THURSDAY' => ['type' => 'THURSDAY', 'isopen' => 0, 'name' => '周四', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
            'FRIDAY' => ['type' => 'FRIDAY', 'isopen' => 0, 'name' => '周五', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
            'SATURDAY' => ['type' => 'SATURDAY', 'isopen' => 0, 'name' => '周六', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
            'SUNDAY' => ['type' => 'SUNDAY', 'isopen' => 0, 'name' => '周日', 'begin_hour' => '', 'begin_minute' => '', 'end_hour' => '', 'end_minute' => ''],
        ];
        if (!empty($advanceInfo['time_limit'])){
            foreach ($advanceInfo['time_limit'] as $item){
                $index = $item['type'];
                if (isset($timeLimit[$index])){
                    $timeLimit[$index]['isopen'] = 1;
                    isset($item['begin_hour']) && $timeLimit[$index]['begin_hour'] = (int) $item['begin_hour'];
                    isset($item['begin_minute']) && $timeLimit[$index]['begin_minute'] = (int) $item['begin_minute'];
                    isset($item['end_hour']) && $timeLimit[$index]['end_hour'] = (int) $item['end_hour'];
                    isset($item['end_minute']) && $timeLimit[$index]['end_minute'] = (int) $item['end_minute'];
                }
            }
        }
        $advanceModel->time_limit = array_values($timeLimit);
        //商家服务类型
        $businessService = !empty($advanceInfo['business_service']) ? (array)$advanceInfo['business_service'] : [];
        $advanceModel->business_service = $businessService;
        $advanceModel->share_friends = isset($advanceInfo['share_friends']) ? (int) $advanceInfo['share_friends'] : 0;
        $advanceModel->save();

        return $baseModel->card_base_id;
    }

    /**
     * 微信用户卡券审核处理
     * @param $eventData
     * @return mixed
     */
    public function handleCardCheck($eventData)
    {
        $base = WxCardBase::where('card_id', $eventData['CardId'])->firstOrFail();
        if ($eventData['Event'] == 'card_pass_check') {
            $base->audit_status = WxCardService::CARD_STATUS_VERIFY_OK;
            $base->audit_result = '';
        } else {
            $base->audit_status = WxCardService::CARD_STATUS_VERIFY_FAIL;
            $base->audit_result = $eventData['RefuseReason'] ?? '';
        }
        return $base->save();
    }

    /**
     * 用户领券处理
     * @param $eventData
     * @return bool
     */
    public function handleUserGet($eventData)
    {
        \DB::beginTransaction();
        try {
            //减少库存数
            $base = WxCardBase::where('card_id', $eventData['CardId'])->firstOrFail();
            $sku = $base->sku;
            $sku['quantity'] = $sku['quantity'] - 1;
            $base->sku = $sku;
            $base->save();

            $receiveModel = WxCardReceive::where('user_card_code', $eventData['UserCardCode'])->where('card_id', $eventData['CardId'])->first();
            if (empty($receiveModel)) {
                $receiveModel = new WxCardReceive;
            }
            $receiveModel->card_type = $base->card_type;
            $receiveModel->card_id = $eventData['CardId'] ?? '';
            $receiveModel->user_openid = $eventData['FromUserName'] ?? '';
            $receiveModel->user_card_code = $eventData['UserCardCode'] ?? '';
            $receiveModel->is_give_by_friend = (int)$eventData['IsGiveByFriend'] ?? 0;
            $receiveModel->friend_user_name = (string)$eventData['FriendUserName'] ?? '';
            $receiveModel->old_user_card_code = (string)$eventData['OldUserCardCode'] ?? '';
            $receiveModel->outer_str = (string)isset($eventData['OuterStr']) ? unicode_decode($eventData['OuterStr']) : (isset($eventData['OuterId']) ? $eventData['OuterId'] : '');
            $receiveModel->is_restore_member_card = (int)$eventData['IsRestoreMemberCard'] ?? 0;
            $receiveModel->receive_time = isset($eventData['CreateTime']) ? date('Y-m-d H:i:s', $eventData['CreateTime']) : date('Y-m-d H:i:s');
            $receiveModel->save();
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 用户转赠事件处理
     * @param $eventData
     * @return bool
     */
    public function handleUserGifting($eventData)
    {
        $transferModel = WxCardTransfer::where('user_card_code', $eventData['UserCardCode'])->where('card_id', $eventData['CardId'])->first();
        if (empty($transferModel)) {
            $transferModel = new WxCardTransfer;
        }
        $transferModel->card_id = $eventData['CardId'] ?? '';
        $transferModel->user_openid = $eventData['FromUserName'] ?? '';
        $transferModel->user_card_code = $eventData['UserCardCode'] ?? '';
        $transferModel->friend_user_openid = $eventData['FriendUserName'] ?? '';
        $transferModel->is_return_back = (int)$eventData['IsReturnBack'] ?? 0;
        $transferModel->is_chat_room = (int)$eventData['IsChatRoom'] ?? 0;
        return $transferModel->save();
    }

    /**
     * 用户删除卡券事件处理
     * @param $eventData
     * @return mixed
     */
    public function handleUserDel($eventData)
    {
        $receiveModel = WxCardReceive::where('user_card_code', $eventData['UserCardCode'])->where('card_id', $eventData['CardId'])->first();
        if ($receiveModel) {
            return $receiveModel->delete();
        }
        return true;
    }

    /**
     * 魔术赋值方法
     * @param $name
     * @param $value
     */
    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    /**
     * 魔术读取属性值方法
     * @param $name
     * @return float|int
     */
    public function __get($name)
    {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
    }
}